﻿using IVBlog.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using static System.Reflection.Metadata.BlobBuilder;

namespace IVBlog.Controllers
{
    public class BackController : Controller
    {

        private readonly IVBlogContext iVBlogContext;
        public BackController(IVBlogContext iVBlog)
        {
            iVBlogContext = iVBlog;
        }

        public bool isLogin()
        {
            if (HttpContext.Session.GetInt32("adminID") == 0 || HttpContext.Session.GetInt32("adminID") == null)
            {
                TempData["LoginState"] = "未登录禁止访问";
                return false;
            }
            return true;
        }

        //后台首页
        public IActionResult Index()
        {
            try
            {
                if (!isLogin())
                {
                    return RedirectToAction("Login","Personal");
                }
                ViewBag.ArticleNum = iVBlogContext.Article.Count();
                ViewBag.CategoryNum = iVBlogContext.Category.Count();
                ViewBag.DynamicNum = iVBlogContext.Dynamic.Count();
                ViewBag.RemarkNum = iVBlogContext.Remark.Count();
                ViewBag.ReplyNum = iVBlogContext.Reply.Count();
                ViewBag.DremarkNum = iVBlogContext.Dremark.Count();
                return View();
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //文章列表
        public IActionResult ArticleList(int pageIndex = 1, int pageSize = 5)
        {
            try
            {
                if (!isLogin())
                {
                    return RedirectToAction("Login", "Personal");
                }
                List<Article> articles = iVBlogContext.Article.Include("Category").ToList();
                var res = iVBlogContext.Article
                    .OrderBy(p => p.ArticleId)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize)
                    .ToList();
                ViewBag.pageIndex = pageIndex;
                ViewBag.pageSize = pageSize;
                //计算总数
                ViewBag.totalRows = articles.Count;
                //计算共有多少页
                ViewBag.totalPage = Math.Ceiling(articles.Count * 1.0 / pageSize);
                return View(res);
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //新增文章
        public IActionResult AddArticle()
        {
            try
            {
                if (!isLogin())
                {
                    return RedirectToAction("Login", "Personal");
                }
                List<Category> categories = iVBlogContext.Category.ToList();
                ViewBag.categories = categories;
                return View();
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //文章添加保存方法 
        [HttpPost]
        //[ValidateInput(false)]
        public ActionResult SaveInfo(string txtTitle,string txtASynopsis,DateTime txtTime,int TypeID)
        {
            try
            {
                Info info = iVBlogContext.Info.First();
                string textValue = Request.Form["txtContent"];
                if (textValue != null)
                {
                    Article article = new Article
                    {
                        CategoryId = TypeID,
                        Aname = txtTitle,
                        Acontent = textValue,
                        Asynopsis = txtASynopsis,
                        Author = info.InfoName,
                        Atime = txtTime,
                        Likes = 0,
                        Astate = 0
                    };
                    iVBlogContext.Article.Add(article);
                    iVBlogContext.SaveChanges();
                    TempData["success"] = "新增文章成功！";
                    return RedirectToAction("AddArticle");
                }
                else
                {
                    TempData["error"] = "新增文章失败！未获取到文章内容";
                    return RedirectToAction("AddArticle");
                }
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }            
        }

        //文章编辑EditArticle
        public IActionResult EditArticle(int id)
        {
            try
            {
                if (!isLogin())
                {
                    return RedirectToAction("Login", "Personal");
                }
                Article article = iVBlogContext.Article.FirstOrDefault(t => t.ArticleId == id);
                List<Category> categories = iVBlogContext.Category.ToList();
                ViewBag.categories = categories;
                ViewBag.cateID = article.CategoryId;
                ViewBag.aName = article.Aname;
                ViewBag.aTime = DateTime.Now;
                ViewBag.aContent = article.Acontent;
                ViewBag.asy = article.Asynopsis;
                ViewBag.aID = article.ArticleId;
                return View();
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //文章编辑保存
        [HttpPost]
        public IActionResult EditArticle(int id, string txtTitle,string txtASynopsis, DateTime txtTime, int TypeID)
        {
            try
            {
                string textValue = Request.Form["txtContent"];
                if (textValue != null)
                {
                    Article article = iVBlogContext.Article.FirstOrDefault(t => t.ArticleId == id);
                    article.Aname = txtTitle;
                    article.AreTime = txtTime;
                    article.Asynopsis = txtASynopsis;
                    article.Acontent = textValue;
                    if (TypeID != article.CategoryId)
                    {
                        if (article.Astate == 1)
                        {
                            Category category = iVBlogContext.Category.FirstOrDefault(t => t.CategoryId == TypeID);
                            category.Cnums += 1;
                            Category category1 = iVBlogContext.Category.FirstOrDefault(t => t.CategoryId == article.CategoryId);
                            category1.Cnums -= 1;
                        }
                        article.CategoryId = TypeID;
                    }
                    iVBlogContext.SaveChanges();
                    TempData["success"] = "文章编辑完成！";
                    return RedirectToAction("EditArticle");
                }
                TempData["error"] = "文章编辑失败！";
                return RedirectToAction("EditArticle");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //文章发布Publish
        [HttpPost]
        public IActionResult Publish(int id)
        {
            try
            {
                Article article = iVBlogContext.Article.FirstOrDefault(t => t.ArticleId == id);
                article.Astate = 1;
                Category category = iVBlogContext.Category.FirstOrDefault(t => t.CategoryId == article.CategoryId);
                category.Cnums += 1;
                if (iVBlogContext.SaveChanges() > 0)
                {
                    return RedirectToAction("ArticleList");
                }
                else
                {
                    TempData["error"] = "发布失败！";
                    return RedirectToAction("ArticleList");
                }
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //文章删除DelArticle
        [HttpPost]
        public IActionResult DelArticle(int id)
        {
            try
            {
                Article article = iVBlogContext.Article.FirstOrDefault(t => t.ArticleId == id);
                Category category = iVBlogContext.Category.FirstOrDefault(t => t.CategoryId == article.CategoryId);
                category.Cnums -= 1;
                iVBlogContext.Article.Remove(article);
                iVBlogContext.SaveChanges();
                return RedirectToAction("ArticleList");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        [HttpPost]
        //新增列表
        public IActionResult TypeAdd(string txtName)
        {
            try
            {
                if (!isLogin())
                {
                    return RedirectToAction("Login", "Personal");
                }
                if (txtName != null)
                {
                    Category category = new Category
                    {
                        Cname = txtName,
                        Cnums = 0
                    };
                    iVBlogContext.Category.Add(category);
                    iVBlogContext.SaveChanges();
                    TempData["success"] = "添加成功！";
                    return RedirectToAction("TypeList");
                }
                TempData["error"] = "添加失败";
                return RedirectToAction("TypeList");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //类别列表
        public IActionResult TypeList(int pageIndex = 1, int pageSize = 5)
        {
            try
            {
                if (!isLogin())
                {
                    return RedirectToAction("Login", "Personal");
                }
                List<Category> categories = iVBlogContext.Category.ToList();
                var res = iVBlogContext.Category
                    .OrderBy(p => p.CategoryId)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize)
                    .ToList();
                ViewBag.pageIndex = pageIndex;
                ViewBag.pageSize = pageSize;
                //计算总数
                ViewBag.totalRows = categories.Count;
                //计算共有多少页
                ViewBag.totalPage = Math.Ceiling(categories.Count * 1.0 / pageSize);
                return View(res);
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //删除类别DelType
        [HttpPost]
        public IActionResult DelType(int id)
        {
            try
            {
                Category category = iVBlogContext.Category.FirstOrDefault(t => t.CategoryId == id);
                iVBlogContext.Category.Remove(category);
                iVBlogContext.SaveChanges();
                return RedirectToAction("DyRemark");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //评论列表
        public IActionResult Remark(int pageIndex = 1, int pageSize = 5)
        {
            try
            {
                if (!isLogin())
                {
                    return RedirectToAction("Login", "Personal");
                }
                List<Remark> remark = iVBlogContext.Remark.ToList();
                var res = iVBlogContext.Remark
                    .OrderBy(p => p.RemarkId)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize)
                    .ToList();
                ViewBag.pageIndex = pageIndex;
                ViewBag.pageSize = pageSize;
                //计算总数
                ViewBag.totalRows = remark.Count;
                //计算共有多少页
                ViewBag.totalPage = Math.Ceiling(remark.Count * 1.0 / pageSize);
                return View(res);
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //评论审核
        public IActionResult EditRemark(int id)
        {
            try
            {
                Remark remark = iVBlogContext.Remark.FirstOrDefault(t=>t.RemarkId == id);
                remark.Rstate = 1;
                if (iVBlogContext.SaveChanges() > 0)
                {
                    TempData["message"] = "审核成功！";
                }
                else
                {
                    TempData["message"] = "审核失败！";
                }
                return RedirectToAction("Remark");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //评论删除DelRemark
        [HttpPost]
        public IActionResult DelRemark(int id)
        {
            try
            {
                Remark remark = iVBlogContext.Remark.FirstOrDefault(t => t.RemarkId == id);
                iVBlogContext.Remove(remark);
                if (iVBlogContext.SaveChanges() > 0)
                {
                    TempData["message"] = "删除成功！";
                }
                else
                {
                    TempData["message"] = "删除失败！";
                }
                return RedirectToAction("Remark");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //评论隐藏HiddenRemark
        [HttpPost]
        public IActionResult HiddenRemark(int id)
        {
            try
            {
                Remark remark = iVBlogContext.Remark.FirstOrDefault(t => t.RemarkId == id);
                remark.Rstate = 2;
                if (iVBlogContext.SaveChanges() > 0)
                {
                    TempData["message"] = "隐藏成功！";
                }
                else
                {
                    TempData["message"] = "隐藏失败！";
                }
                return RedirectToAction("Remark");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //评论恢复BlockRemark
        [HttpPost]
        public IActionResult BlockRemark(int id)
        {
            try
            {
                Remark remark = iVBlogContext.Remark.FirstOrDefault(t => t.RemarkId == id);
                remark.Rstate = 1;
                if (iVBlogContext.SaveChanges() > 0)
                {
                    TempData["message"] = "隐藏成功！";
                }
                else
                {
                    TempData["message"] = "隐藏失败！";
                }
                return RedirectToAction("Remark");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //回复列表
        public IActionResult ReplyList(int pageIndex = 1, int pageSize = 5)
        {
            try
            {
                if (!isLogin())
                {
                    return RedirectToAction("Login", "Personal");
                }
                List<Reply> replies = iVBlogContext.Reply.ToList();
                var res = iVBlogContext.Reply
                    .OrderBy(p => p.RemarkId)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize)
                    .ToList();
                ViewBag.pageIndex = pageIndex;
                ViewBag.pageSize = pageSize;
                //计算总数
                ViewBag.totalRows = replies.Count;
                //计算共有多少页
                ViewBag.totalPage = Math.Ceiling(replies.Count * 1.0 / pageSize);
                return View(res);
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //回复审核 EditReply
        public IActionResult EditReply(int id)
        {
            try
            {
                Reply reply = iVBlogContext.Reply.FirstOrDefault(t => t.ReplyId == id);
                reply.ReplyState = 1;
                if (iVBlogContext.SaveChanges() > 0)
                {
                    TempData["message"] = "审核成功！";
                }
                else
                {
                    TempData["message"] = "审核失败！";
                }
                return RedirectToAction("ReplyList");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //回复删除DelReply
        [HttpPost]
        public IActionResult DelReply(int id)
        {
            try
            {
                Reply reply = iVBlogContext.Reply.FirstOrDefault(t => t.ReplyId == id);
                iVBlogContext.Remove(reply);
                if (iVBlogContext.SaveChanges() > 0)
                {
                    TempData["message"] = "删除成功！";
                }
                else
                {
                    TempData["message"] = "删除失败！";
                }
                return RedirectToAction("ReplyList");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //回复隐藏HiddenReply
        [HttpPost]
        public IActionResult HiddenReply(int id)
        {
            try
            {
                Reply reply = iVBlogContext.Reply.FirstOrDefault(t => t.ReplyId == id);
                reply.ReplyState = 2;
                if (iVBlogContext.SaveChanges() > 0)
                {
                    TempData["message"] = "隐藏成功！";
                }
                else
                {
                    TempData["message"] = "隐藏失败！";
                }
                return RedirectToAction("ReplyList");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //回复恢复BlockReply
        [HttpPost]
        public IActionResult BlockReply(int id)
        {
            try
            {
                Reply reply = iVBlogContext.Reply.FirstOrDefault(t => t.ReplyId == id);
                reply.ReplyState = 1;
                if (iVBlogContext.SaveChanges() > 0)
                {
                    TempData["message"] = "隐藏成功！";
                }
                else
                {
                    TempData["message"] = "隐藏失败！";
                }
                return RedirectToAction("ReplyList");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //留言列表
        public IActionResult DyRemark(int pageIndex = 1, int pageSize = 4)
        {
            try
            {
                if (!isLogin())
                {
                    return RedirectToAction("Login", "Personal");
                }
                List<Dremark> dremarks = iVBlogContext.Dremark.ToList();
                var res = iVBlogContext.Dremark
                    .OrderBy(p => p.DremarkId)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize)
                    .ToList();
                ViewBag.pageIndex = pageIndex;
                ViewBag.pageSize = pageSize;
                //计算总数
                ViewBag.totalRows = dremarks.Count;
                //计算共有多少页
                ViewBag.totalPage = Math.Ceiling(dremarks.Count * 1.0 / pageSize);
                return View(res);
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //留言审核EditDyRemark
        [HttpPost]
        public IActionResult EditDyRemark(int id)
        {
            try
            {
                Dremark dremark = iVBlogContext.Dremark.FirstOrDefault(t => t.DremarkId == id);
                dremark.Drstate = 1;
                if (iVBlogContext.SaveChanges() > 0)
                {
                    TempData["message"] = "审核成功！";
                }
                else
                {
                    TempData["message"] = "审核失败！";  
                }
                return RedirectToAction("DyRemark");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //留言删除DelDyRemark
        [HttpPost]
        public IActionResult DelDyRemark(int id)
        {
            try
            {
                Dremark dremark = iVBlogContext.Dremark.FirstOrDefault(t => t.DremarkId == id);
                iVBlogContext.Remove(dremark);
                if (iVBlogContext.SaveChanges() > 0)
                {
                    TempData["message"] = "删除成功！";
                }
                else
                {
                    TempData["message"] = "删除失败！";  
                }
                return RedirectToAction("DyRemark");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //留言隐藏HiddenDremark
        [HttpPost]
        public IActionResult HiddenDremark(int id)
        {
            try
            {
                Dremark dremark = iVBlogContext.Dremark.FirstOrDefault(t => t.DremarkId == id);
                dremark.Drstate = 2;
                if (iVBlogContext.SaveChanges() > 0)
                {
                    TempData["message"] = "隐藏成功！";
                }
                else
                {
                    TempData["message"] = "隐藏失败！";      
                }
                return RedirectToAction("DyRemark");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //留言展示BlockDremark
        [HttpPost]
        public IActionResult BlockDremark(int id)
        {
            try
            {
                Dremark dremark = iVBlogContext.Dremark.FirstOrDefault(t => t.DremarkId == id);
                dremark.Drstate = 1;
                if (iVBlogContext.SaveChanges() > 0)
                {
                    TempData["message"] = "展示成功！";
                }
                else
                {
                    TempData["message"] = "展示失败！";
                }
                return RedirectToAction("DyRemark");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //动态列表Dynamic
        public IActionResult DynamicList(int pageIndex = 1, int pageSize = 5)
        {
            try
            {
                if (!isLogin())
                {
                    return RedirectToAction("Login", "Personal");
                }
                List<Dynamic> dynamics = iVBlogContext.Dynamic.ToList();
                var res = iVBlogContext.Dynamic
                    .OrderBy(p => p.DynamicId)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize)
                    .ToList();
                ViewBag.pageIndex = pageIndex;
                ViewBag.pageSize = pageSize;
                //计算总数
                ViewBag.totalRows = dynamics.Count;
                //计算共有多少页
                ViewBag.totalPage = Math.Ceiling(dynamics.Count * 1.0 / pageSize);
                return View(res);
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //写动态DynamicAdd
        public IActionResult DynamicAdd()
        {
            try
            {
                if (!isLogin())
                {
                    return RedirectToAction("Login", "Personal");
                }
                return View();
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //动态保存方法SaveDynamic
        [HttpPost]
        public IActionResult SaveDynamic(string txtContent,DateTime txtTime)
        {
            try
            {
                if (txtTime == null)
                {
                    txtTime = DateTime.Now;
                }
                Dynamic dynamic = new Dynamic
                {
                    Dcontent = txtContent,
                    Dtime = txtTime,
                    Dlikes = 0,
                    Dstate = 0
                };
                iVBlogContext.Dynamic.Add(dynamic);
                iVBlogContext.SaveChanges();
                return RedirectToAction("DynamicList");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //动态伪删除的方法EditDynamic(隐藏)
        [HttpPost]
        public IActionResult EditDynamic(int id)
        {
            try
            {
                Dynamic dynamic = iVBlogContext.Dynamic.FirstOrDefault(t => t.DynamicId == id);
                dynamic.Dstate = 1;
                if (iVBlogContext.SaveChanges()>0)
                {
                    TempData["message"] = "删除成功！";
                }
                else
                {
                    TempData["message"] = "删除失败！";  
                }
                return RedirectToAction("DynamicList");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }

        //动态恢复的方法BlockDynamic(显示)
        [HttpPost]
        public IActionResult BlockDynamic(int id)
        {
            try
            {
                Dynamic dynamic = iVBlogContext.Dynamic.FirstOrDefault(t => t.DynamicId == id);
                dynamic.Dstate = 0;
                if (iVBlogContext.SaveChanges() > 0)
                {
                    TempData["message"] = "恢复成功！";
                }
                else
                {
                    TempData["message"] = "恢复失败！";
                }
                return RedirectToAction("DynamicList");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = ex.Message;
                return RedirectToAction("Error", "Error");
            }
        }
    }
}
